package com.pan.insist.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pan.insist.annotation.CacheLock;
import com.pan.insist.annotation.OperateLog;
import com.pan.insist.base.BaseController;
import com.pan.insist.constant.CommonConstant;
import com.pan.insist.constant.OperateConstant;
import com.pan.insist.exception.ViewException;
import com.pan.insist.model.TestModel;
import com.pan.insist.service.TestService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Arrays;


/**
* <p>
* 测试-前端控制器
* </p>
*
* @author 黄阿能
* @since 2020-01-09
*/

@Log4j2
@Controller
@RequestMapping("/test")
public class TestController extends BaseController {
    @Resource
    private TestService testService;

    private final static String PREFIX = "test/";

    /**
    * 跳转到测试首页
    */
    @GetMapping("/list")
    public String list() {
        return PREFIX + LIST;
    }

    @ResponseBody
    @GetMapping("/listJson")
    @OperateLog(operateModule = "测试管理", operateType = OperateConstant.SELECT, operateDesc = "查看测试事件列表！")
    public JSONObject listJson(Page<TestModel> iPage, TestModel testModel) {
        QueryWrapper<TestModel> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(testModel.getTestName())) {
            queryWrapper.lambda().like(TestModel::getTestName, testModel.getTestName());
        }
        iPage = testService.page(iPage, queryWrapper);
        return page2LayTablePage(iPage);
    }

    @GetMapping("/view")
    @CacheLock(prefix = "view")
    @OperateLog(operateModule = "测试管理", operateType = OperateConstant.VIEW, operateDesc = "查看测试类！")
    public String view(String id, ModelMap modelMap) {
        if (StringUtils.isBlank(id)) {
            throw new ViewException("id不存在");
        }
        TestModel testModel = testService.getById(id);
        modelMap.put("testModel", testModel);
        return PREFIX + VIEW;
    }

    @GetMapping("update")
    public String toUpdate(String id, ModelMap modelMap) {
        if (StringUtils.isBlank(id)) {
            throw new ViewException("请选择一条数据！");
        }

        TestModel testModel = testService.getById(id);
        if (testModel == null) {
            log.info("查询不到数据！");
            throw new ViewException("请选择一条数据！");
        }
        modelMap.put("testModel", testModel);
        return PREFIX + INPUT;
    }

    @ResponseBody
    @PostMapping("/update")
    @CacheLock(prefix = "test-update")
    @OperateLog(operateModule = "测试管理", operateType = OperateConstant.UPDATE, operateDesc = "修改测试事件！")
    public JSONObject update(TestModel testModel) {
        JSONObject jsonObject = validate(testModel, CommonConstant.DATA_UPDATE_TYPE);
        Integer code = jsonObject.getInteger(CommonConstant.AjaxCode.CODE);
        if (code.equals(CommonConstant.AjaxCode.FAIL_CODE)) {
            return jsonObject;
        }

        jsonObject = new JSONObject();
        boolean flag = testService.updateById(testModel);
        if (flag) {
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "修改测试数据成功！");
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.SUCCESS_CODE);
        } else {
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "修改测试数据失败！");
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
        }
        return jsonObject;
    }

    @GetMapping("save")
    public String toSave() {
        // 查询全部的角色
        return PREFIX + INPUT;
    }

    @ResponseBody
    @PostMapping("save")
    @CacheLock(prefix = "save")
    public JSONObject save(TestModel testModel) {
        JSONObject jsonObject = validate(testModel, CommonConstant.DATA_SAVE_TYPE);
        Integer code = jsonObject.getInteger(CommonConstant.AjaxCode.CODE);
        if (code.equals(CommonConstant.AjaxCode.FAIL_CODE)) {
            return jsonObject;
        }
        jsonObject = new JSONObject();
        try {
            testService.save(testModel);
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.SUCCESS_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "保存数据成功！");
        } catch (Exception e) {
            log.error("保存测试数据异常！原因：{}", e.getMessage());
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, e.getMessage());
        }
        return jsonObject;
    }

    /**
    * 批量删除
    *
    * @param ids id集合
    */
    @ResponseBody
    @PostMapping("delete")
    @CacheLock(prefix = "test-delete")
    public JSONObject delete(String ids) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isEmpty(ids)) {
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "请至少选择一条数据！");
            return jsonObject;
        }
        try {
            testService.removeByIds(Arrays.asList(ids.split(CommonConstant.DOC_FLAG)));
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.SUCCESS_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "删除测试数据成功！");
        } catch (Exception e) {
            log.error("删除失败！原因： {}", e.getMessage());
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "删除测试数据失败！");
        }

        return jsonObject;
    }


    /**
    * 检测数据是否合格
    *
    * @param testModel 测试数据对象
    * @param type      1： 修改 2：存储
    */
    protected JSONObject validate(TestModel testModel, int type) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
        if (testModel == null) {
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "对象不能为空！");
            return jsonObject;
        }

        if (type == CommonConstant.DATA_UPDATE_TYPE) {
            if (StringUtils.isEmpty(testModel.getId())) {
                jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "请至少选择一个对象数据！");
                return jsonObject;
            }
            // 判断用户是否存在
            TestModel test = testService.getById(testModel.getId());
            if (test == null) {
                jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "该数据被删除，已经不存在！");
                return jsonObject;
            }

        } else if (type == CommonConstant.DATA_SAVE_TYPE) {

        } else {
            jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.FAIL_CODE);
            jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "数据类型错误！");
            return jsonObject;
        }
        jsonObject.put(CommonConstant.AjaxCode.CODE, CommonConstant.AjaxCode.SUCCESS_CODE);
        jsonObject.put(CommonConstant.AjaxCode.MESSAGE, "数据验证成功！");
        return jsonObject;
    }

}
